﻿using CozeDomain.Entities;
using CozeDomain.IRepositories;
using CozeDto.SaleApplyForDtos;
using D.UtilFreesqlOrm;
using StackExchange.Profiling.Data;


namespace CozeDomain.Repositories
{
    public class SaleApplyForEntityRepository : BaseRepository<SaleApplyForEntity>, ISaleApplyForEntityRepository
    {
        public SaleApplyForEntityRepository(IFreeSql db) : base(db)
        {
        }

        public async Task<Tuple<long, List<RepSaleApplyForInfo>>> QuerySaleApplyForPagesAsync(ReqQuerySaleApplyForPage reqQuerySaleApplyForPage)
        {
            var where = _db.Select<SaleApplyForEntity, UserEntity>()
                                                              .LeftJoin((a, b) => a.UserId == b.Id)
                                                              .Where((a, b) => a.TenantId == reqQuerySaleApplyForPage.TenantId)
                                                              .WhereIf(!string.IsNullOrEmpty(reqQuerySaleApplyForPage.Account), (a, b) => b.Account.Contains(reqQuerySaleApplyForPage.Account));

            var dbres = await where.Count(out var totalCount)
                                                       .Page(reqQuerySaleApplyForPage.PageNo, reqQuerySaleApplyForPage.PageSize)
                                                       .ToListAsync((a, b) => new RepSaleApplyForInfo
                                                       {
                                                           Account = b.Account,
                                                           Link = a.Link,
                                                           RefundMethod = a.RefundMethod,
                                                           Reason = a.Reason,
                                                           Status = a.Status,
                                                           CreateTime = a.CreateTime,
                                                           CreateUser = a.CreateUser,
                                                           Id = a.Id,
                                                           UpdateTime = a.UpdateTime,
                                                           UpdateUser = a.UpdateUser
                                                       });

            return new Tuple<long, List<RepSaleApplyForInfo>>(totalCount, dbres);
        }

        public async Task<List<RepSaleApplyForInfo>> GetSaleApplyForListAsync(string userId)
        {
            return await _db.Select<SaleApplyForEntity>().Where(m => m.UserId == userId).ToListAsync(m => new RepSaleApplyForInfo()
            {
                Link = m.Link,
                RefundMethod = m.RefundMethod,
                Reason = m.Reason,
                Status = m.Status,
                CreateTime = m.CreateTime,
            });
        }
    }
}
